package com.tt.payee.business;

import com.tt.payee.api.ResponseResult;
import com.tt.payee.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;


/**
 * 全局业务异常处理
 *
 * @author Tang
 * @Description: 后台用户登录
 * @date:2020-02-27 11:01
 */
@Slf4j
@ControllerAdvice
public class BusinessExceptionHandler {

    @ExceptionHandler(value = AbortException.class)
    @ResponseBody
    public ResponseResult<?> handle(AbortException ex){
        try{
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.flush();
            sw.flush();
            log.info("数据校验不通过，errorMsg：{}",sw);
        }catch(Exception e1){
            log.error("errorMsg：{}",e1.getMessage());
        }

        return new ResponseResult<>(ex.getCode(), ex.getMsg(), null);
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<?> handlerException(HttpServletRequest request, Exception ex) {
        ResponseResult error = new ResponseResult();

        // 业务异常
        if (ex instanceof BusinessException) {
            error.setCode(((BusinessException) ex).getCode());
            error.setMessage(ex.getMessage());
            log.warn("[全局业务异常]\r\n业务编码：{}\r\n异常记录：{}", error.getCode(), error.getMessage());
            log.error(error.getMessage(), ex);
        }

        // 未知错误
        else {
            error.setCode(BusinessStatus.UNKNOWN.getCode());
            error.setMessage(BusinessStatus.UNKNOWN.getMessage());
        }

        return new ResponseEntity<>(error, HttpStatus.OK);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult<?>  handle(Exception ex){

        try{
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.flush();
            sw.flush();
            log.error("出现错误，errorMsg：{}",sw);
        }catch(Exception e1){
            log.error("errorMsg：{}",e1.getMessage());
        }

        return new ResponseResult<>(ResultCode.INTERNAL_ERROR.getCode(), ResultCode.INTERNAL_ERROR.getMessage(), null);

    }

}
